<template>
  <q-page class="q-pa-md wrapBox" v-loading="loading">
    <div class="nav">
      <el-breadcrumb separator="/">
          <el-image
            src="/svgs/titleIcon.svg"
            style="width: 17px; margin: 0 10px 0 0"
            fit
          />
        <el-breadcrumb-item>{{ $t('dataCenter') }}</el-breadcrumb-item>
        <el-breadcrumb-item><span style="color: #333">{{ $t('dataSet') }}</span></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="datasetBox" style="position: relative">
      <div class="contentBox_title">{{ $t('dataSet') }}</div>
      <div class="contentBox">
        <el-row class="mb-4" style="margin-bottom: 15px">
          <div>
            <el-input
              v-model.trim="searchName"
              placeholder="搜索数据集名称"
              spellcheck="false"
              @keyup.enter="filterDataset('1')"
            >
              <template #prepend>
                <el-select
                  v-model="typeValue"
                  placeholder="全部"
                  style="width: 150px; background-color: #fff"
                >
                  <el-option
                    v-for="item in dataSetData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    @click="filterDataset('2')"
                  />
                </el-select>
              </template>
              <template #append>
                <el-button :icon="Search" @click="filterDataset('1')" />
              </template>
            </el-input>
          </div>
          <div class="rightBox">
            <el-button
              style="background-color: #3d5ce4; width: 80px"
              type="primary"
              @click="toCreateDataSet"
              >{{ $t('newBuilt') }}</el-button
            >
            <el-button
              :class="{ mergeBtnHover: !mergeButtonShow }"
              style="width: 80px; margin-left: 8px"
              :style="{
                cursor: !mergeButtonShow ? 'not-allowed' : '',
                backgroundColor: !mergeButtonShow ? '' : '#fff!important',
              }"
              @click="mergeClick"
              >{{ $t('merge') }}</el-button
            >
          </div>
        </el-row>
        <el-table
          ref="tabelList"
          :data="resData.results"
          style="width: 100%; font-size: 14px"
          :cell-style="cellStyle"
          :header-cell-style="headerCellStyle"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column
            align="left"
            prop="title"
            label="数据集名称"
            width="180"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                style="font-size: 14px"
                @click="toDataSetDetail( scope.row.id, scope.row.version_latest, scope.row.status, scope.row.version_id )"
              >
               <span class="overflowText">{{ scope.row.title }}</span>
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            align="left"
            prop="dataset_type_zh"
            label="数据类型"
            width="140"
          />
          <el-table-column
            align="left"
            prop="creator"
            label="创建人"
            width="100"
          />
          <el-table-column
            align="left"
            prop="create_time"
            label="创建时间"
            width="190"
          />
          <el-table-column
            align="left"
            prop="description"
            label="数据集说明"
            width="100"
          >
            <template #default="scope">
              {{ scope.row.description ? scope.row.description : '-' }}
            </template>
          </el-table-column>
          <el-table-column
            align="left"
            prop="status"
            label="创建状态"
            width="140"
          >
            <template #default="scope">
              <StatusBoxCpn :status="scope.row.status" :gap="5" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="操作">
            <template #default="scope">
              <template v-if="scope.row.status === 'success'">
              <el-button v-for="(item, index) in labelsObj" :key="index" style="font-size: 14px"
                v-show="userStatus ? true : scope.row.creator === userInfoName" link type="primary" size="small" @click="
                  labelsFun(
                    item,
                    scope.row.id,
                    scope.$index,
                    scope.row.title,
                    scope.row.data_type,
                    scope.row.label_type,
                    scope.row.dataset_type_zh,
                    scope.row.id,
                    scope.row.version_id
                  )
                  ">
                  {{ item }}
                </el-button>
              </template>
              <template v-else-if="scope.row.status == 'pause'">
                <el-button
                  v-show="userStatus ? true : scope.row.creator === userInfoName"
                  link
                  type="primary"
                  size="medium"
                  @click="
                    handleContinueUpload({
                      project_id: projectId,
                      dataset_id: scope.row.id,
                      version_id: scope.row.version_id,
                      upload_id: scope.row.upload_id,
                    })
                  "
                  >继续上传
                </el-button>
              </template>
              <template v-else>
                <div
                  style="
                    position: absolute;
                    top: 50%;
                    transform: translateY(-50%);
                  "
                >
                  <el-tooltip
                    class="box-item"
                    effect="light"
                    content="创建过程: Uploading -> Merging -> Importing -> Success"
                    placement="top-start"
                  >
                    <div class="d-dot" style="position: relative; left: 0">
                      <span style="color: #606266"> 飞速创建中 </span>
                      <span class="d-dot-ani"></span>
                    </div>
                  </el-tooltip>
                </div>
              </template>
            </template>
          </el-table-column>
          <template #empty>
            <div class="noData">暂无数据</div>
          </template>
        </el-table>
      </div>
      <div
        class="row"
        style="
          justify-content: flex-end;
          margin-top: 10px;
          background-color: #fff;
          padding: 10px 0;
        "
      >
        <el-pagination
          background
          v-model:current-page="pageData.page"
          v-model:page-size="pageData.page_size"
          :small="false"
          :disabled="false"
          :show-jumper="true"
          layout="total, prev, pager, next, sizes, jumper, total"
          :total="resData.count"
          :page-sizes="[10, 20, 50]"
          @size-change="sizeChange"
          @current-change="changePage"
        />
      </div>
      <el-dialog
        v-model="dialogFormVisible"
        title="导入数据"
        width="500"
        :show-close="false"
        :close-on-click-modal="false"
      >
        <upload-data-set
          v-if="dialogFormVisible"
          @formData="formData"
          :userData="listIndex"
        ></upload-data-set>
        <template #footer>
          <span class="c-dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="formDataFun">导入</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 发布新版本 -->
      <el-dialog
        :close-on-click-modal="false"
        v-model="dialogNewVersion"
        title="发布数据新版本"
        width="400"
        :show-close="false"
        @close="resetForm(ruleFormRef)"
      >
        <el-form
          ref="ruleFormRef"
          :model="formLabelAlign"
          :rules="rules"
          label-position="right"
          label-width="100px"
          style="max-width: 460px"
        >
          <el-form-item label="版本名称：" prop="title">
            <el-input
              v-model.trim="formLabelAlign.title"
              input-style="width:180px"
            />
          </el-form-item>
          <el-form-item label="版本描述：" prop="description">
            <el-input
              v-model.trim="formLabelAlign.description"
              input-style="width:180px"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="c-dialog-footer">
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button type="primary" @click="createNewVersion(ruleFormRef)">
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!--数据集合并 start-->
      <el-dialog
        v-model="mergeDialogShow"
        title="数据集合并"
        width="500px"
        :close-on-click-modal="false"
        class="mergeDialogShow"
      >
        <el-form
          style="padding: 0 50px; margin-top: 20px"
          ref="mergeFormRef"
          :model="mergeForm"
          :rules="mergeFormRules"
          :label-position="'right'"
          label-width="110px"
          status-icon
          @submit.prevent
        >
          <el-form-item label="数据集名称:" prop="title">
            <el-input v-model="mergeForm.title" style="width: 100%" />
          </el-form-item>
          <el-form-item label="数据集类型:">
            <p style="margin: 0">{{ mergeFormType }}</p>
          </el-form-item>
          <el-form-item label="数据集说明:">
            <el-input
              class="textArea"
              v-model="mergeForm.description"
              type="textarea"
              autocomplete="off"
              :rows="5"
              placeholder="请输入"
              spellcheck="false"
              show-word-limit
              maxlength="100"
            />
          </el-form-item>
          <el-form-item label="输入版本号:" prop="version">
            <el-input
              v-model="mergeForm.version"
              placeholder="请输入版本号,例: v1、v001"
              spellcheck="false"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div
            style="
              display: flex;
              justify-content: flex-end;
              padding: 0;
              margin-right: 28px;
            "
          >
            <el-button
              @click="cancelMergeForm(mergeFormRef)"
              style="width: 80px; background-color: #fff !important"
              >取消</el-button
            >
            <el-button
              type="primary"
              @click="mergeBtn(mergeFormRef)"
              style="width: 80px"
              >合并</el-button
            >
          </div>
        </template>
      </el-dialog>
      <!--数据集合并 end-->

      <!--数据处理建模 start-->
      <el-dialog
        v-model="dataProcessingModel"
        title="建模"
        width="400px"
        :show-close="true"
        :close-on-click-modal="false"
        class="processingModel"
      >
        <el-form
          style="padding: 0 50px"
          ref="dataProcessingFormRef"
          :model="dataProcessingModelForm"
          :rules="dataProcessingModelRules"
          :label-position="'right'"
          label-width="110px"
          status-icon
          @submit.prevent
        >
          <el-form-item label="数据集名称：">
            <p style="margin: 0">{{ datasetTitle }}</p>
          </el-form-item>
          <el-form-item label="数据类型：">
            <p style="margin: 0">{{ datasetTypeZh }}</p>
          </el-form-item>
          <el-form-item label="版本选择：" prop="version">
            <el-select
              v-model="dataProcessingModelForm.version"
              class="m-2"
              placeholder="选择版本"
              style="width: 300px"
              popper-class="dropdown"
            >
              <el-option
                v-for="item in versionList"
                :key="item.id"
                :label="item.title"
                :value="item.title"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div style="display: flex;justify-content: flex-end;padding: 0">
            <el-button @click="cancelDataProcessingModel(dataProcessingFormRef)"
              style="background-color: #fff!important;">{{ $t('cancle') }}</el-button>
            <el-button type="primary" @click="webModeling(dataProcessingFormRef)">{{ $t('enterModeling') }}</el-button>
          </div>
        </template>
      </el-dialog>
      <!--数据处理建模 end-->

      <!-- 删除 -->
      <q-dialog v-model="dialogDeleteData">
        <q-card style="width: 450px; height: 170px">
          <q-card-section>
            <div class="text-h6" style="font-size: 17px">
              <el-icon
                style="
                  color: #ffa940;
                  display: inline-block;
                  vertical-align: middle;
                  margin-top: -3px;
                  font-size: 25px;
                "
              >
                <WarningFilled />
              </el-icon>
              <span style="font-size: 16px; margin-left: 5px; color: #ffa940"
                >删除提醒</span
              >
            </div>
          </q-card-section>
          <q-card-section class="q-pt-none" style="padding-left: 45px">
            <div style="line-height: 22px; color: #666">
              确定删除本数据集吗？删除后不可恢复，请谨慎操作！
            </div>
            <div style="line-height: 22px; color: #666">
              如果数据集下有数据集版本则需要先删除数据集版本。
            </div>
          </q-card-section>
          <q-card-actions
            align="right"
            class="text-primary"
            style="margin-right: 20px; margin-top: 10px"
          >
            <el-button @click="deleteData">确认删除</el-button>
            <el-button type="primary" v-close-popup>放弃删除</el-button>
          </q-card-actions>
        </q-card>
      </q-dialog>

      <!--导出 start-->
      <el-dialog
        :close-on-click-modal="false"
        v-model="dialogExportModel"
        title="导出数据"
        width="400"
        :show-close="false"
        @close="resetForm(ruleFormRef)"
        class="dialogExportModel"
      >
        <el-form
          ref="exportFormRef"
          :model="exportForm"
          :rules="exportRules"
          label-position="right"
          label-width="120px"
          style="max-width: 460px"
        >
          <el-form-item label="数据集名称：">
            <p style="margin: 0">{{ datasetTitle }}</p>
          </el-form-item>
          <el-form-item label="数据类型：">
            <p style="margin: 0">{{ datasetTypeZh }}</p>
          </el-form-item>
          <el-form-item label="版本选择：" prop="version">
            <el-select
              v-model="exportForm.version"
              class="m-2"
              placeholder="选择版本"
              popper-class="dropdown"
            >
              <el-option
                v-for="item in versionList"
                :key="item.id"
                :label="item.title"
                :value="item.title"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div style="display: flex; justify-content: flex-end; padding: 0">
            <el-button
              @click="resetExportForm(exportFormRef)"
              style="background-color: #fff"
              >取消</el-button
            >
            <el-button type="primary" @click="exportModelData(exportFormRef)"
              >导出</el-button
            >
          </div>
        </template>
      </el-dialog>
      <!--导出 end-->

      <el-dialog
        v-model="platformReUploadStore.reUploadModal"
        title="继续上传"
        width="60%"
        :modal="false"
        :before-close="closeContinueUploadModal"
        destroy-on-close
      >
        <el-table :data="dialogContinueUpload.fileList" height="377" style="width: 100%" :header-cell-style="headerCellStyle"
          v-loading="!dialogContinueUpload.fileList.length"
        >
          <el-table-column
            prop="row_name"
            label="文件名称"
            width="100"
            show-overflow-tooltip
          />
          <el-table-column prop="total_size_calc" label="文件大小" />
          <el-table-column prop="dataset_title" label="所属数据集" />
          <el-table-column prop="version_title" label="所属版本" />
          <el-table-column prop="create_time" label="上传时间" width="180" />

          <el-table-column prop="progress" label="已经上传进度">
            <template #default="scope">
              <el-progress :stroke-width="10" :percentage="scope.row.progress"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="progress">
            <template #default="scope">
              <template
                v-if="
                  dialogContinueUpload.fileListStatusControl[
                    scope.row.dataset_id
                  ][scope.row.row_name].isPassCheck
                "
              >
                <el-icon color="#21ba45">
                  <Check />
                </el-icon>
              </template>
              <template v-else>
                <el-upload
                  class="upload-demo"
                  :auto-upload="false"
                  :show-file-list="false"
                  :onChange="(uploadFile: UploadFile, uploadFiles: UploadFiles) =>
                  handleContinueChange(uploadFile, uploadFiles, scope.row.row_name,scope.row.total_size, scope.row.dataset_id )"
                >
                  <q-btn
                    round
                    dense
                    flat
                    color="grey-8"
                    style="display: flex; align-items: center"
                  >
                    <el-icon>
                      <CaretRight />
                    </el-icon>
                    <q-tooltip effect="light"
                      >选择相同的文件，继续上传</q-tooltip
                    >
                  </q-btn>
                </el-upload>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="startContinueUpload">
              继续创建
            </el-button>
          </span>
        </template>
      </el-dialog>
      <div class="temp" v-if="tempShow"></div>
    </div>
  </q-page>
</template>
<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import StatusBoxCpn from 'components/StatusBoxCpn.vue';
import type { FormInstance, FormRules } from 'element-plus';
import {
  ElMessage,
  ElNotification,
  ElPagination,
  UploadFile,
  UploadFiles,
} from 'element-plus';
import {
  batchUploadDatasetData,
  createVersion,
  deleteModelData,
  exportDataSet,
  getDatasetList,
  mergeDatasetsFun,
  validateDatasetListTitle,
  versionManage,
} from 'src/api/dataset';
import uploadDataSet from 'src/components/uploadDataSet.vue';
import { dataSetStore } from 'src/stores/dataSet';
import { onMounted, reactive, ref, shallowRef, watch } from 'vue';
import { useRouter } from 'vue-router';
const userStatus = JSON.parse(localStorage.getItem('user') || '{}').status; //判断用户是否是项目创建人或项目管理员
const userInfoName = localStorage.getItem('username'); //获取用户登录的用户名
import {dataSetData} from 'src/utils/useData';
import {UploadList, usePlatformUploadStore} from "stores/platform-upload";
import {authedApi} from "src/utils/axios";
import {getUnCompleteFileList} from "src/api/dataCenter";
import {ContinueUploadInfo, usePlatformReUploadStore} from "stores/platform-reupload";

const router = useRouter();
const projectId = router.currentRoute.value.params.project_id;
const store = dataSetStore();
const platformUploadStore = usePlatformUploadStore();
const platformReUploadStore = usePlatformReUploadStore();
const pageData = dataSetStore().pageData;
const searchName = ref('');
const listIndex = ref();
const typeValue = ref('');
const oneDataId = ref();
const versionIdDate = ref(0); //版本id
const datasetTitle = ref(); //数据集名称
const datasetTypeZh = ref(); //数据类型
const versionList = ref([]); //版本选择
const loading = ref(true);
const dialogFormVisible = ref(false);
const dialogNewVersion = ref(false);
const dialogExportModel = ref(false);
const dialogDeleteData = ref(false);
const dataProcessingModel = ref(false); //数据处理建模
const tempShow = ref(false);

const dialogContinueUpload = reactive({
  fileList: [] as UploadList[],
  fileListStatusControl: {} as Record<
    string,
    Record<string, { isPassCheck: boolean }>
  >,
  curContinueInfo: {} as ContinueUploadInfo,
});

const formLabelAlign = reactive({
  title: '',
  description: '',
});
const exportForm = reactive({
  version: '',
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  title: [
    {
      required: true,
      message: '版本名称不能为空',
      trigger: ['blur', 'change'],
    },
  ],
});
let mergeButtonShow = ref(false); //合并按钮是否生效
let mergeDialogShow = ref(false); //合并弹框生效
const mergeFormRef = ref();
const exportFormRef = ref();
const mergeForm = reactive({
  title: '',
  description: '',
  dataset_type: '',
  version: '',
  dataset_ids: <any>[],
});

//单元表格样式
const headerCellStyle = {
  background: '#f9f9f9',
  color: '#333',
  textAlign: 'left',
  fontWeight: '500',
  fontSize: '14px'
};
let mergeFormType = ref(''); //数据类型---数据集合并
const validateTitle = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('数据集名称不能为空'));
    return;
  }
  if (value.length < 4) {
    callback(new Error('字段长度最小长度为4'));
    return;
  }
  if (value.length > 16) {
    callback(new Error('字段长度最大长度为16'));
    return;
  }
  let params = {
    title: mergeForm.title,
  };
  validateDatasetListTitle(projectId, params)
    .then((res: any) => {
      if (res.data.msg) {
        callback(new Error(res.data.msg));
      }
      callback();
    })
    .catch((err: any) => {
      callback(new Error('校验接口报错'));
    });
};
const mergeFormRules = reactive({
  title: [{ required: true, validator: validateTitle, trigger: 'blur' }],
  version: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
});
const dataProcessingModelForm = reactive({
  version: '',
});
const dataProcessingModelRules = reactive({
  version: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
});
const exportRules = reactive({
  version: [{ required: true, message: '版本选择不能为空', trigger: 'blur' }],
});
const uploadData = shallowRef({
  file_ids: <any>[],
  is_labeled: false,
  import_mode: 'local',
});
const dataProcessingFormRef = ref(); //数据处理建模表单ref
const cellStyle = () => {
  return { height: '56px' };
};
//取消数据处理建模按钮
const cancelDataProcessingModel = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  if (dataProcessingModel.value) {
    formEl.resetFields();
    dataProcessingModel.value = false;
  }
};

const closeContinueUploadModal = (done: any) => {
  platformUploadStore.setVueUploadComponentFileListEmpty();
  done();
};

const handleContinueUpload = async (req: ContinueUploadInfo) => {
  platformReUploadStore.openModal();
  const fileListResponse = await getUnCompleteFileList(req);
  const lists = fileListResponse.data;
  const listControl: Record<string, Record<string, any>> = {};
  lists.forEach((list) => {
    listControl[String(list.dataset_id)] =
      listControl[String(list.dataset_id)] || {};
    listControl[String(list.dataset_id)][list.row_name] = {
      isPassCheck: false,
    };

    platformReUploadStore.mapperUploadId(
      String(list.dataset_id),
      String(list.upload_id),
      list.row_name
    );
  });
  platformReUploadStore.setReUploadList(lists);
  dialogContinueUpload.fileListStatusControl = listControl;
  dialogContinueUpload.fileList = lists;
  dialogContinueUpload.curContinueInfo = { ...req };
};

const startContinueUpload = async () => {
  let isNoPass = false;
  Object.keys(dialogContinueUpload.fileListStatusControl).forEach(
    (dataset_id) => {
      Object.keys(
        dialogContinueUpload.fileListStatusControl[dataset_id]
      ).forEach((filename) => {
        if (
          dialogContinueUpload.fileListStatusControl[dataset_id][filename]
            .isPassCheck == false
        ) {
          isNoPass = true;
        }
      });
    }
  );
  if (isNoPass) {
    ElMessage.warning('请将所有的文件上传之后，在继续创建');
    return;
  }
  await platformReUploadStore.startContinueUpload(
    dialogContinueUpload.curContinueInfo
  );
};

const handleContinueChange = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles,
  filename: string,
  filesize: number,
  dataset_id: string
) => {
  if (uploadFile.name !== filename || uploadFile?.raw?.size !== filesize) {
    ElMessage.warning('请上传和之前一样的文件');
    return;
  }
  dialogContinueUpload.fileListStatusControl[dataset_id][filename].isPassCheck =
    true;
  platformUploadStore.pushFileList(uploadFile);
};

const fileUploadState = ref(true);

function formData(e: any) {
  let urlArr = e.value.choices.map((item: any, index: number) => {
    return item.id;
  });
  uploadData.value = {
    file_ids: urlArr,
    is_labeled: e.value.is_labeled,
    import_mode: e.value.import_mode,
  };
  fileUploadState.value = e.value.fileUpload;
}

// 切换页
function changePage(currentPage: any) {
  dataSetStore().setPageData(currentPage);
  getDataset();
}

function sizeChange(pageSize: any) {
  dataSetStore().setPageData(1);
  dataSetStore().setPageSizeData(pageSize);
  getDataset();
}

// 新建数据集
function toCreateDataSet() {
  router.push({ name: 'dataset-create', params: { project_id: projectId } });
}

function formDataFun() {
  if (fileUploadState.value == true) {
    ElMessage.error('文件正在上传,请等待');
    return;
  }
  if (uploadData.value.file_ids && uploadData.value.file_ids.length == 0) {
    ElMessage.error('请选择上传文件');
    return;
  }

  batchUploadDatasetData(projectId, oneDataId.value, uploadData.value)
    .then((res: any) => {
      dialogFormVisible.value = false;
      ElNotification({
        title: 'Success',
        message: '导入数据成功',
        type: 'success',
      });
    })
    .finally(() => {
      getDataset();
      uploadData.value.file_ids = [];
    });
}

// 取消创建数据集
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  if (dialogNewVersion.value) {
    formEl.resetFields();
    dialogNewVersion.value = false;
  }
};

// 新建数据版本
const createNewVersion = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      createVersion(projectId, oneDataId.value, formLabelAlign)
        .then((res: any) => {
          dialogNewVersion.value = false;
          ElNotification({
            title: 'Success',
            message: '新建数据版本成功',
            type: 'success',
          });
        })
        .finally(() => {
          formLabelAlign.title = ' ';
          formLabelAlign.description = ' ';
        });
    } else {
      console.log('error submit!', fields);
    }
  });
};

//关闭导出弹框
const resetExportForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogExportModel.value = false;
};

//进入建模
const webModeling = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('进入建模');
    }
  });
};

// 导出数据集
const exportModelData = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('versionIdDate',versionIdDate.value);
      exportDataSet(projectId, oneDataId.value, versionIdDate.value, {
        version: exportForm.version,
      }).then((res: any) => {
        let jsonObj = JSON.stringify(res.data);
        //type表示要转换的数据格式
        const blob = new Blob([jsonObj], {
          type: 'application/json',
        });
        // 根据 blob生成 url链接
        const objectURL = URL.createObjectURL(blob);
        const aTag = document.createElement('a');
        aTag.href = objectURL;
        // 设置保存后的文件名称
        aTag.download = `${res.data.dataset}.json`;
        // 给 a 标签添加点击事件
        aTag.click();
        // 释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。
        URL.revokeObjectURL(objectURL);
      });
      formEl.resetFields();
      dialogExportModel.value = false;
    }
  });
};

// 数据详情页面
function toDataSetDetail(
  datasetId: number,
  version: string,
  status: string,
  version_id: number
) {
  if (status != 'success') {
    if (status != 'failure') {
      ElNotification({
        title: 'Warning',
        message: `当前状态是 ${status}, 请等待数据集创建成功，之后在进入。`,
        type: 'warning',
      });
    } else {
      ElNotification({
        title: 'Error',
        message: `当前状态是 ${status}, 请进行数据集的断点续传`,
        type: 'error',
      });
    }
    return;
  }
  const dataSetObj = dataSetStore();
  dataSetObj.dataset(datasetId);
  dataSetObj.versionset(version_id);
  dataSetStore().chooseNumberSet('1');
  router.push({ name: 'dataset-detail', params: { project_id: projectId } });
}

let resData: any = reactive({
  count: 0,
  next: null,
  previous: null,
  results: [],
});
const labelsObj = ref([
  '建模',
  '全部版本',
  // "导入",
  // '发布新版本',
  // '全部版本',
  // '数据特征',//数据特征内容暂时不显示
  '删除',
  '导出',
]);

function filterDataset(num: string) {
  dataSetStore().setPageData(1);
  getDataset();
}

async function getDataset() {
  loading.value = true;
  let obj: any = {};
  if (typeValue.value != '') obj.dataset_type = typeValue.value;
  if (searchName.value != '') obj.title = searchName.value;
  obj = Object.assign(obj, pageData);

  const res = await getDatasetList(projectId, obj);

  resData = res.data;

  loading.value = false;
}

watch(
  () => platformUploadStore.platformDatasetStatusChange,
  async () => {
    loading.value = true;
    await getDataset();
    tempShow.value = !tempShow.value;
    loading.value = false;
  }
);

//多选
const handleSelectionChange = (val: any) => {
  let dataList = JSON.parse(JSON.stringify(val));
  if (dataList && dataList.length > 0) {
    mergeFormType.value = dataList[0].dataset_type_zh;
    mergeForm.dataset_type = dataList[0].dataset_type;
    let everyResult = dataList.every(
      (item: any) => item.dataset_type === dataList[0].dataset_type
    );
    if (everyResult) {
      mergeForm.dataset_ids = dataList.map((item: any) => item.id);
      mergeForm.dataset_type = dataList[0].dataset_type;
      if (val && val.length > 1) {
        mergeButtonShow.value = true;
      } else {
        mergeButtonShow.value = false;
      }
    } else {
      mergeButtonShow.value = false;
      ElMessage.error('非相同数据类型不能合并');
    }
  } else {
    mergeButtonShow.value = false;
  }
};
//点击合并
const mergeClick = () => {
  if (mergeButtonShow.value) {
    mergeDialogShow.value = true;
  }
};
//点击取消
const cancelMergeForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  mergeDialogShow.value = false;
};

function labelsFun(
  str: string,
  num: number,
  index: number,
  title: string,
  data_type: string,
  label_type: string,
  dataset_type_zh: string,
  id: number,
  versionId: number
) {
  versionIdDate.value = versionId;
  oneDataId.value = id;
  listIndex.value = index;
  datasetTitle.value = title;
  datasetTypeZh.value = dataset_type_zh;
  if (str === '建模') {
    dataProcessingModel.value = true;
    versionManage(projectId, id).then((res: any) => {
      versionList.value = res.data.results;
    });
  }
  if (str === '全部版本') {
    const dataSetObj = dataSetStore();
    dataSetObj.dataset(id);
    dataSetObj.versionset(versionId);
    dataSetStore().chooseNumberSet('2');
    router.push({ name: 'dataset-detail', params: { project_id: projectId } });
  }
  if (str === '删除') dialogDeleteData.value = true;
  if (str === '导出') {
    dialogExportModel.value = true;
    versionManage(projectId, id).then((res: any) => {
      versionList.value = res.data.results;
    });
  }
}

function deleteData() {
  deleteModelData(projectId, oneDataId.value)
    .then((res: any) => {
      loading.value = true;
      dialogDeleteData.value = false;
      ElMessage({
        message: '数据集已删除',
        type: 'success',
      });
    })
    .finally(() => {
      getDataset();
    })
    .catch((error) => {
      dialogDeleteData.value = false;
    });
}

//合并数据集

const mergeBtn = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      mergeDatasetsFun(projectId, mergeForm).then((res) => {
        if (res.data.msg === '合并成功') {
          mergeDialogShow.value = false;
          getDataset();
        }
      });
    }
  });
};

onMounted(() => {
  // 通过store.quickStart.quickFlow判断是否显示快速入门提示
  if (store.quickStart.quickFlow) {
    store.setQuickStart({
      tipsPopup: true,
      quickFlow: true,
      flowNumber: store.quickStart.flowNumber,
    });
  }
  getDataset();
});
const uploadDataType = (data_type: string, label_type: string) => {
  if (label_type == 'question_answering') {
    return 'json';
  } else {
    switch (data_type) {
      case 'Image':
        return 'jpg,png,gif,bmp,svg,webp,jpeg';
      case 'Text':
        return 'txt';
      case 'TimeSeries':
        return 'csv,tsv';
    }
  }
};
</script>

<style lang="scss" scoped>
.wrapBox {
  padding: 0 !important;

  .nav {
    display: flex;
    align-items: center;
    padding-left: 20px;
    cursor: pointer;
    background-color: var(--nav-bg-color);
    height: 46px;

    ::v-deep .el-breadcrumb {
      display: flex;
      align-items: center;
    }
  }

  .datasetBox {
    margin: 0 20px;

    .contentBox_title {
      color: var(--title);
      font-weight: 500;
      font-size: 16px;
      padding: 15px 15px;
      border-bottom: 1px solid #e5e6eb;
      background-color: #ffffff !important;
    }

    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
    }
  }
}

//超出显示省略号
.overflowText {
  text-overflow: ellipsis;
  overflow: hidden;
  width: 180px;
  white-space: nowrap;
  cursor: pointer;
  text-align: left;
}
//end



.el-dialog__title {
  font-weight: 500;
}

//CSS 来隐藏右下角的双斜杠图标。
.textArea ::v-deep .el-textarea__inner {
  resize: none !important;
}

//合并按钮悬停样式
.mergeBtnHover {
  border: 1px solid rgb(204, 204, 204);
  background-color: rgb(243, 243, 243);
  color: rgb(208, 208, 208);
}

//面包屑斜杆
:deep(.el-breadcrumb__separator) {
  font-size: 12px !important;
  color: #c9cdd4 !important;
}

//面包屑字体颜色
:deep(.el-breadcrumb__inner) {
  color: #666 !important;
}

::v-deep .el-pagination__goto {
  margin-left: 20px;
}

::v-deep .processingModel .el-dialog__body,
::v-deep .dialogExportModel .el-dialog__body,
::v-deep .mergeDialogShow .el-dialog__body {
  padding: 10px 0 0 0 !important;
}

::v-deep .processingModel .el-dialog__footer,
::v-deep .dialogExportModel .el-dialog__footer,
::v-deep .mergeDialogShow .el-dialog__footer {
  padding-top: 0 !important;
}

::v-deep .q-card__section {
  padding-bottom: 5px !important;
}

::v-deep .el-select-dropdown__item {
  padding: 0 !important;
}

//下拉框选项样式
::v-deep .el-select-dropdown__item.hover,
::v-deep .el-select-dropdown__item:hover {
  background-color: rgb(237, 239, 252) !important;
}

//下拉框背景颜色
.dropdown {
  .el-select-dropdown__item.selected {
    font-weight: 500 !important;
  }

  .el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover {
    background: #3d5ce41a;
    color: #3d5ce4;
    font-weight: 400;
    font-size: 14px;
    text-align: left;
  }
}

::v-deep disabled,
::v-deep .disabled *,
::v-deep [disabled],
::v-deep [disabled] * {
  outline: 10px !important;
  cursor: pointer !important;
}

//数据处理建模表头加下划线 start
::v-deep .el-dialog__header {
  border-bottom: 1px solid rgb(234, 234, 234);
}

//end
.pagination {
  margin: 3rem auto;
  display: flex;
  justify-content: center;
}

::v-deep .el-dialog__body {
  padding-top: 10px;
}

.rightBox {
  position: absolute;
  right: 0;
}

.el-dropdown {
  color: #3d5ce4;
  font-size: 12px;
  line-height: 24px;
  margin-left: 15px;
}

.deleteTip {
  .el-dialog__body {
    padding: 10px;
    text-align: center;
  }
}

.c-dialog-footer {
  display: flex;
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid rgb(234, 234, 234);

  .button {
    cursor: pointer;
    width: 50%;
    margin: 0;
    border: none;
    text-align: center;
    line-height: 40px;
  }

  .button:nth-child(1) {
    color: #1d1d1d;
    border-right: 1px solid rgb(234, 234, 234);
  }

  .button:nth-child(2) {
    color: #1b5bd8;
  }
}

.d-dot-ani {
  display: inline-block;
  height: 12px;
  line-height: 12px;
  overflow: hidden;
}

.d-dot-ani::after {
  display: inline-table;
  white-space: pre;
  content: '\A.\A..\A...';
  animation: spin 2s steps(4) infinite;
}

@keyframes spin {
  to {
    -webkit-transform: translateY(-48px);
    transform: translateY(-48px);
  }
}

//点击下拉框，去掉输入框蓝色高亮显示
:deep(.el-input) {
  --el-input-focus-border: #fff;
  --el-input-transparent-border: 0 0 0 0px;
  --el-input-border-color: var(--el-border-color);
  --el-input-hover-border: 0px !important;
  --el-input-hover-border-color: var(--el-border-color);
  --el-input-focus-border-color: var(--el-border-color);
  --el-input-clear-hover-color: var(--el-border-color);
}
</style>
